// 导入WebDriver和By
import { WebDriver, By, until } from 'selenium-webdriver';
import { NoteContent } from '../../lib/search.js';
import { captureFirstImage, extractCollectCount, extractCommentCount, extractContent, extractImageCount, extractLikeCount, extractPublishDate, extractTitle } from './extractData.js';
import { checkUiAutomator2Status, restartUiAutomator2 } from './systemBack.js';
import { clickCopyButton, clickShareButton, getClipboardLink } from './clipboard.js';
import { performSmoothScroll } from './scroll.js';
import { AndroidConfig } from '../../profile/android/android_config.js';
import { ContentState, ContentStateMachine } from '../../lib/statemachine.js';

export async function extractDataFromPageSource(contentMachine: ContentStateMachine,driver: WebDriver): Promise<NoteContent> {
  
    // 初始化内容对象
  const content: NoteContent = {
    title: '',
    content: '',
    images: "",
    imagesCount: 0,
    link: '',
    likes: 0,
    collects: 0,
    comments: 0,
    noteType: '',
    publishTime: ''
  };      
  
  try {
    console.log('开始从页面源码提取数据...');
    
    const pageSource = await driver.getPageSource();     
    // 提取文本内容（从text属性中）
    const textMatches = pageSource.match(/text="([^"]*[\u4e00-\u9fa5]+[^"]*)"/g);
    if (textMatches) {
      const texts = textMatches.map(match => match.replace(/text="([^"]+)"/, '$1'));
      console.log('提取到的文本内容:', texts); 
    }

    // 提取content-desc
    const contentDescMatches = pageSource.match(/content-desc="([^"]+)"/g);
    if (contentDescMatches) {
      const contentDescs = contentDescMatches.map(match => match.replace(/content-desc="([^"]+)"/, '$1'));
      // console.log('提取到的content-desc:', contentDescs.slice(0, 10));
      console.log('提取到的content-desc:', contentDescs);

      // 提取点赞数
      const likeCount = extractLikeCount(contentDescs);
      console.log("提取到的点赞数:", likeCount);

      // 提取收藏数
      const collectCount = extractCollectCount(contentDescs);
      console.log("提取到的收藏数:", collectCount);

      // 提取评论数
      const commentCount = extractCommentCount(contentDescs);
      console.log("提取到的评论数:", commentCount);

      // 提取图片数量
      const imageCount = extractImageCount(contentDescs);
      console.log("提取到的图片数量:", imageCount);

      
      // 提取首图
      const firstImage = await captureFirstImage(driver, new Date().getTime().toString());
      console.log("提取到的首图:", firstImage);
      
      // 设计爬取逻辑 image_state 用 1 crawl/ video_state 用 2 crawl
      if (contentMachine.state === ContentState.IMAGE_TEXT) {

        // adb 下滑
        await performSmoothScroll(driver, AndroidConfig.device.deviceName, 3, 'standard');

        // 提取文本内容
        const pageSource = await driver.getPageSource();     
        // 提取文本内容（从text属性中）
        const textMatches = pageSource.match(/text="([^"]*[\u4e00-\u9fa5]+[^"]*)"/g);
        if (textMatches) {
          const texts = textMatches.map(match => match.replace(/text="([^"]+)"/, '$1'));
          console.log('提取到的文本内容:', texts); 

          //提取标题
        const title = extractTitle(texts.slice(0,5));
        console.log("提取到的标题:", title);

        // 提取文本内容
        const context = extractContent(texts);
        console.log("提取到的文本内容:", content);

        // 提取发布时间
        const publishTime = await extractPublishDate(driver,texts);
        console.log("提取到的发布时间:", publishTime);

        content.title = title || "";
        content.content = context || "";
        content.publishTime = publishTime || "";
        content.noteType = '图片';
        }

        // // 提取content-desc
        // const contentDescMatches = pageSource.match(/content-desc="([^"]+)"/g);
        // if (contentDescMatches) {
        //   const contentDescs = contentDescMatches.map(match => match.replace(/content-desc="([^"]+)"/, '$1'));
        //   console.log('提取到的content-desc:', contentDescs);
        // }

        

      }else{
        // 爬取视频的title and content

        content.noteType = '视频';
      }

      // 提取链接
      const link = await extactCurrentUrl(driver);
      console.log("提取到的链接:", link);

      content.likes = likeCount;
      content.collects = collectCount;
      content.comments = commentCount ;
      content.imagesCount = imageCount ;

      content.images = firstImage || "";
      content.link = link || "";
   
    }
    return content;
    
  } catch (error) {
    console.error('提取页面数据失败:', error);
    return content;
  }
}

// 从作者主页提取数据
export async function extractDataFromProfile(driver: WebDriver): Promise<number> {
    
  try {
    console.log('开始从作者主页提取数据...');
    
    await driver.sleep(3000);
    const pageSource = await driver.getPageSource();        

    // 提取文本内容
    const textMatches = pageSource.match(/text="([^"]*[\u4e00-\u9fa5]+[^"]*)"/g);
    if (textMatches) {
      const texts = textMatches.map(match => match.replace(/text="([^"]+)"/, '$1'));
      console.log('提取到的文本内容:', texts); 
    }

    // 提取content-desc
    const contentDescMatches = pageSource.match(/content-desc="([^"]+)"/g);
    if (contentDescMatches) {
      const contentDescs = contentDescMatches.map(match => match.replace(/content-desc="([^"]+)"/, '$1'));
      console.log('提取到的content-desc:', contentDescs);

      // 提取粉丝数（支持"万"为单位）
    let fansCount = 0;
    const fansEntry = contentDescMatches.find(desc => desc.includes('粉丝'));
    if (fansEntry) {
        const match = fansEntry.match(/([\d.]+)万?粉丝/);
        if (match && match[1]) {
            fansCount = parseFloat(match[1]);
            if (fansEntry.includes('万')) {
                fansCount *= 10000;
            }
        }
    }
    console.log("提取到的粉丝数:", fansCount); // 输出: 104000
      return fansCount;
    }
    return 0;

  } catch (error) {
    console.error('提取页面数据失败:', error);
    return 0;
  }
}

/**
 * 取当前页面URL（适用于移动端）
 */
export async function extactCurrentUrl(driver: WebDriver, maxRetries: number = 3): Promise<string | null> {
  // await driver.sleep(2000)
  
      await driver.sleep(1000)
      try {
          console.log(`尝试获取URL...`);
          
          // 检查 UiAutomator2 服务状态
          const isServiceRunning = await checkUiAutomator2Status(driver);
          if (!isServiceRunning) {
              console.log('UiAutomator2 服务异常，重启服务...');
              await restartUiAutomator2(driver);
              await driver.sleep(3000);
          }
          
          await driver.sleep(1000);
          // 点击分享
          await clickShareButton(driver);

          await driver.sleep(1000);
          // 点击 复制链接
          await clickCopyButton(driver);

          // 等待复制操作完成
          await driver.sleep(1000);
          const link = await getClipboardLink(driver);
          if (link) {
              console.log(`尝试成功获取URL: ${link}`);
              return link;
          }
          
          console.log(`尝试未获取到URL`);
          
      } catch (error) {
          console.error(`获取URL失败:`, error);
          
          // 处理 UiAutomator2 服务崩溃
          if (error instanceof Error && error.message.includes('instrumentation process is not running')) {
              try {
                  await restartUiAutomator2(driver);
                  await driver.sleep(5000);
              } catch (restartError) {
                  console.error('重启服务失败:', restartError);
              }
          }
      }
  
  console.log(`尝试仍无法获取URL`);
  return null;
}

